import { query } from "../mysqlQuery.js";
import Joi from "joi";
import { getRandomId } from "../common/index.js";
import jwt from "jsonwebtoken";
import SDTime from "silly-datetime"; //时间格式化处理插件
const secretKey = "itheima No1 ^_^";
//注册账号
function add(req, res, next) {
  const schema = Joi.object().keys({
    user_name: Joi.string().min(2).max(20).required(),
    phone: Joi.string()
      .regex(/^1\d{10}$/)
      .required(),
    pwd: Joi.string()
      .min(7)
      .max(11)
      .regex(/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/)
      .required(),
    sex: Joi.string().valid("男", "女").required(), //只能是男或女
    age: Joi.number().min(0).max(200).required(), //最小0-200岁
    uuid: Joi.required(),
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (result.error == null) {
    query([
      {
        sql: "select * from users where uuid=?",
        values: [req.body.uuid],
      },
    ])
      .then((first) => {
        if (first[0].rows.length > 0) {
          res.send({
            code: 400,
            msg: "该手机已注册过账号！",
          });
        } else {
          query([
            {
              sql: "select * from users where phone=?",
              values: [req.body.phone],
            },
          ])
            .then((out) => {
              if (out[0].rows.length > 0) {
                res.send({
                  code: 400,
                  msg: "该手机号已被使用！",
                });
              } else {
                query([
                  {
                    sql: "insert into users (user_id,user_name,phone,pwd,sex,age,uuid,create_time,head_imgurl) values (?,?,?,?,?,?,?,?,?);",
                    values: [
                      getRandomId(8),
                      req.body.user_name.trim(),
                      req.body.phone,
                      req.body.pwd.trim(),
                      req.body.sex,
                      req.body.age,
                      req.body.uuid,
                      SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
                      "https://img0.baidu.com/it/u=2580450068,3312521163&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
                    ],
                  },
                ])
                  .then((result) => {
                    console.log("日志位置在regeister.js文件:");
                    console.log(result);
                    res.send({
                      code: 200,
                      msg: "注册成功！",
                    });
                  })
                  .catch((err) => {
                    next(err);
                  });
              }
            })
            .catch((error) => {
              next(error);
            });
        }
      })
      .catch((errp) => {
        next(errp);
      });
  } else {
    next(result.error);
  }
}
//最后一次登录时间
function newLoginTime(req, res, next) {
  query([
    {
      sql: "update users set login_lastTime=? where user_id=?;",
      values: [
        SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
        req.auth.user_id,
      ],
    },
  ])
    .then((out) => {
      res.send({
        code: 200,
        msg: "修改成功！",
      });
    })
    .catch((err) => {
      next(err);
    });
}
//扫码登录
function scanLogin(req, res, next) {
  console.log(req.body);
  const schema = Joi.object().keys({
    user_id: Joi.string().required(),
    uuid: Joi.required(),
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (!result.error) {
    query([
      {
        sql: "select * from users where user_id=?;",
        values: [req.body.user_id],
      },
      {
        sql: "update users set uuid=? where user_id=?;",
        values: [req.body.uuid, req.body.user_id],
      },
    ])
      .then((out) => {
        if (out[0].rows.length > 0) {
          const tokenStr = jwt.sign(
            {
              user_id: req.body.user_id, //用户ID，识别用户
              token_createTime: SDTime.format(
                new Date(),
                "YYYY-MM-DD HH:mm:ss"
              ), //创建时间
              token_expirationTime: SDTime.format(
                new Date().getTime() + 7 * 24 * 60 * 60 * 1000,
                "YYYY-MM-DD HH:mm:ss"
              ), //过期时间
            },
            secretKey,
            {
              expiresIn: "7 days",
            }
          );
          res.send({
            code: 200,
            msg: "登录成功！",
            token: tokenStr,
          });
        } else {
          res.send({
            code: 400,
            msg: "未找到该用户信息!",
            token: "",
          });
        }
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//账号登录
function select(req, res, next) {
  const schema = Joi.object().keys({
    phone: Joi.string()
      .regex(/^1\d{10}$/)
      .required(),
    pwd: Joi.string()
      .regex(/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/)
      .required(),
    uuid: Joi.string(),
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  let queryArr = [];
  if (result.error == null) {
    if (req.body.uuid) {
      queryArr = [
        {
          sql: "select phone,pwd,user_id from users where phone=? and pwd=?;",
          values: [req.body.phone, req.body.pwd.trim()],
        },
        {
          //登录获取用户当前包标识，方便后续找回密码验证
          sql: "update users set uuid=? where phone=?;",
          values: [req.body.uuid, req.body.phone],
        },
      ];
    } else {
      queryArr = [
        {
          sql: "select phone,pwd,user_id from users where phone=? and pwd=?;",
          values: [req.body.phone, req.body.pwd.trim()],
        },
      ];
    }
    query(queryArr)
      .then((result) => {
        console.log("日志位置在regeister.js文件:");
        console.log(result[0].rows);
        if (result[0].rows.length > 0) {
          const tokenStr = jwt.sign(
            {
              user_id: result[0].rows[0].user_id, //用户ID，识别用户
              token_createTime: SDTime.format(
                new Date(),
                "YYYY-MM-DD HH:mm:ss"
              ), //创建时间
              token_expirationTime: SDTime.format(
                new Date().getTime() + 7 * 24 * 60 * 60 * 1000,
                "YYYY-MM-DD HH:mm:ss"
              ), //过期时间
            },
            secretKey,
            {
              expiresIn: "7 days",
            }
          );
          res.send({
            code: 200,
            msg: "登录成功！",
            token: tokenStr,
          });
        } else {
          res.send({
            code: 400,
            msg: "该账号不存在！",
          });
        }
        // TODO_03：在登录成功之后，调用 jwt.sign() 方法生成 JWT 字符串。并通过 token 属性发送给客户端
        // 参数1：用户的信息对象
        // 参数2：加密的秘钥
        // 参数3：配置对象，可以配置当前 token 的有效期
        // 记住：千万不要把密码加密到 token 字符中
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//注销账号
function lose(req, res, next) {
  const schema = Joi.object().keys({
    user_id: Joi.string().min(6).max(8).required(),
  });
  const result = Joi.validate(req.auth, schema, { allowUnknown: true });
  if (result.error == null) {
    query([
      {
        sql: "delete from users where user_id=?;", //删除用户表数据
        values: [req.auth.user_id],
      },
      {
        sql: "delete from books where user_id=?;", //删除书籍表数据
        values: [req.auth.user_id],
      },
      {
        sql: "delete from chapters where user_id=?;", //删除章节表数据
        values: [req.auth.user_id],
      },
    ])
      .then((result) => {
        console.log("日志位置在regeister.js文件:");
        console.log(result);
        res.send({
          code: 200,
          msg: "删除成功！",
        });
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//查询账号信息
function selectCountInfo(req, res, next) {
  const schema = Joi.object().keys({
    user_id: Joi.string().min(6).max(8).required(),
  });
  const result = Joi.validate(req.auth, schema, { allowUnknown: true });
  if (result.error == null) {
    query([
      {
        sql: "select * from users where user_id=?;",
        values: [req.auth.user_id],
      },
    ])
      .then((out) => {
        console.log("日志位置在regeister.js文件:");
        console.log(out[0].rows);
        if (out[0].rows.length > 0) {
          out[0].rows[0].create_time = SDTime.format(
            out[0].rows[0].create_time,
            "YYYY-MM-DD HH:mm:ss"
          );
          out[0].rows[0].login_lastTime = SDTime.format(
            out[0].rows[0].login_lastTime,
            "YYYY-MM-DD HH:mm:ss"
          );
          out[0].rows[0].update_time = SDTime.format(
            out[0].rows[0].update_time,
            "YYYY-MM-DD HH:mm:ss"
          );
          res.send({
            code: 200,
            msg: "查询成功",
            data: out[0].rows,
          });
        } else {
          res.send({
            code: 400,
            msg: "未查找到相关用户信息",
            data: null,
          });
        }
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//修改账号信息
function put(req, res, next) {
  const schema = Joi.object().keys({
    head_imgUrl: Joi.string(),
    phone: Joi.string().regex(/^1\d{10}$/),
    pwd: Joi.string().regex(/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/),
    sex: Joi.string().valid("男", "女"), //只能是男或女
    age: Joi.number().min(0).max(200), //最小0-200岁
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (result.error == null) {
    let sql = "update users set ";
    let values = [];
    Object.keys(result.value).forEach((item, index) => {
      sql += item + "=?,";
      values.push(result.value[item]);
    });
    sql += "update_time=? where user_id=?;";
    values.push(SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"));
    values.push(req.auth.user_id);
    query([
      {
        sql,
        values,
      },
    ])
      .then((result) => {
        console.log("日志位置在regeister.js文件:");
        console.log(result);
        res.send({
          code: 200,
          msg: "修改成功！",
        });
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//修改账号名
function putCount(req, res, next) {
  const schema = Joi.object().keys({
    user_name: Joi.string().min(2).max(10).required(),
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (!result.error) {
    query([
      {
        sql: "update users set user_name=?,update_time=? where user_id=?",
        values: [
          req.body.user_name,
          SDTime.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
          req.auth.user_id,
        ],
      },
    ])
      .then((out) => {
        res.send({
          code: 200,
          msg: "修改成功",
          data: out[0],
        });
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
//找回密码接口
function findBackPwd(req, res, next) {
  const schema = Joi.object().keys({
    uuid: Joi.required(),
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (!result.error) {
    query([
      {
        sql: "select * from users where uuid=?;",
        values: [req.body.uuid],
      },
    ])
      .then((out) => {
        if (out[0].rows.length > 0) {
          res.send({
            code: 200,
            userInfo: {
              pwd: out[0].rows[0].pwd,
              count: out[0].rows[0].phone,
            },
            msg: "找回成功！",
          });
        } else {
          res.send({
            code: 200,
            userInfo: null,
            msg: "该手机未注册过或者卸载并重新的新包！",
          });
        }
      })
      .catch((err) => {
        next(err);
      });
  } else {
    next(result.error);
  }
}
export {
  add,
  select,
  lose,
  put,
  selectCountInfo,
  putCount,
  scanLogin,
  findBackPwd,
  newLoginTime,
};
